﻿using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Tools.Extension;
using System.Collections.ObjectModel;
using YY.Admin.Core;
using YY.Admin.FluentValidation;
using YY.Admin.Services.Service;
using YY.Admin.Services.Service.User;

namespace YY.Admin.ViewModels.SysManage
{
    public class UserEditDialogViewModel : BaseViewModel, IDialogResultable<bool>
    {
        private SysUser? _sysUser;
        private readonly ISysUserService _sysUserService;

        public SysUserValidator SysUserValidator { get; private set; }

        public SysUser? SysUser
        {
            get => _sysUser;
            set {
                SetProperty(ref _sysUser, value);
            } 
        }

        public bool IsAddMode => SysUser?.Id == 0;

        public string DialogTitle => IsAddMode ? "新增用户" : "编辑用户";

        // 性别枚举列表
        //public List<KeyValuePair<string, int>> GenderList =>
        //    Enum.GetValues(typeof(GenderEnum))
        //        .Cast<GenderEnum>()
        //        .Select(e => new KeyValuePair<string, int>(e.GetDescription(), (int)e))
        //        .ToList();

        public ObservableCollection<GenderEnum> GenderList { get; }
            = new ObservableCollection<GenderEnum>(Enum.GetValues(typeof(GenderEnum)).Cast<GenderEnum>().ToArray());

        public ObservableCollection<StatusEnum> StatusOptions { get; }
            = new ObservableCollection<StatusEnum>(Enum.GetValues(typeof(StatusEnum)).Cast<StatusEnum>().ToArray());

        //// 状态枚举列表
        //public List<KeyValuePair<string, int>> StatusList =>
        //    Enum.GetValues(typeof(StatusEnum))
        //        .Cast<StatusEnum>()
        //        .Select(e => new KeyValuePair<string, int>(e.GetDescription(), (int)e))
        //        .ToList();

        public DelegateCommand SaveCommand { get; private set; }
        public DelegateCommand CancelCommand { get; private set; }

        public DelegateCommand<object> StatusSelectedCommand { get; }

        private bool _result;
        public bool Result { get => _result; set => SetProperty(ref _result, value); }
        public Action? CloseAction { get; set; }

        public UserEditDialogViewModel(
            ISysUserService sysUserService,
            IContainerExtension container,
            IRegionManager regionManager) : base(container, regionManager)
        {
            _sysUserService = sysUserService;
            SysUserValidator = new SysUserValidator(sysUserService);
            //SysUser = new SysUser();

            StatusSelectedCommand = new DelegateCommand<object>(OnStatusSelected);

            SaveCommand = new DelegateCommand(async () => await SaveUserAsync());
            CancelCommand = new DelegateCommand(() => CloseAction?.Invoke());
        }

        private void OnStatusSelected(object statusObj)
        {
            if (statusObj is StatusEnum status)
            {
                SysUser?.Status = status;
            }
        }

        public async Task SaveUserAsync()
        {
            try
            {
                if (IsAddMode)
                {
                    var result = await _sysUserService.CreateAsync(SysUser!);
                    Result = result > 0;
                    if (Result)
                    {
                        Growl.Success(new GrowlInfo
                        {
                            Message = "新增用户成功！",
                            ShowDateTime = false,
                            WaitTime = 1
                        });
                    }
                    else
                    {
                        Growl.Error("新增用户失败！");
                        return;
                    }
                }
                else
                {
                    var result = await _sysUserService.UpdateAsync(SysUser!);
                    Result = result > 0;
                    if (Result)
                    {
                        Growl.Success("修改用户成功！");
                    }
                    else
                    {
                        Growl.Error("修改用户失败！");
                        return;
                    }
                }

                // 关闭对话框
                CloseAction?.Invoke();
            }
            catch (Exception ex)
            {
                Growl.Error($"操作失败：{ex.Message}");
            }
        }

        // 初始化编辑数据
        public void InitializeForEdit(UserOutput user)
        {
            if (user != null)
            {
                SysUser = new SysUser
                {
                    Id = user.Id,
                    //Account = user.Account,
                    RealName = user.RealName,
                    NickName = user.NickName,
                    //Phone = user.Phone,
                    Sex = user.Sex,
                    Birthday = user.Birthday,
                    Age = user.Age,
                    //AccountType = user.AccountType,
                    Status = user.Status
                };
            }
        }

        // 初始化新增数据
        public void InitializeForAdd()
        {
            SysUser = new SysUser();
            //IsAddMode = true;
            RaisePropertyChanged(nameof(IsAddMode));
            RaisePropertyChanged(nameof(DialogTitle));
        }

        //private readonly SysUserValidator _addValidator = new SysUserValidator(true);
        //private readonly SysUserValidator _editValidator = new SysUserValidator(false);

        //public string this[string columnName]
        //{
        //    get
        //    {
        //        if (SysUser == null) return string.Empty;

        //        var validator = IsAddMode ? _addValidator : _editValidator;
        //        var result = validator.Validate(SysUser);

        //        var error = result.Errors.FirstOrDefault(e => e.PropertyName == columnName);
        //        return error?.ErrorMessage;
        //    }
        //}


    }
}
